'''
泰无忧·百万防癌保
'''

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json, time
from common.helper import Helper


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "泰无忧百万防癌保"

    # 生成产品数据
    def genProductInfo(self):

        # 年龄段
        years = [str(i) for i in range(18, 81)]

        # 保障计划
        plan = ["1010A0G201", "1010A0G202"]

        # 有无社保 0 无社保 1 有社保
        socialSec = ["0", "1"]

        for v in product(years, plan, socialSec):
            # 写入数据库
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(v[0], v[1], v[2]))
            self.mysql._conn.commit()

            print("产品信息写入数据库成功")

    # 执行爬虫
    def requestJson(self, dt=None):

        if dt["plan"] == "1010A0G201":

            data = {
                "calculateData": {
                    "insuredInfo": [{
                        "calinsuredRelationship": "01",
                        "calinsuredBirth": "2001-10-31",
                        "minimum": 18,
                        "maximum": 80
                    }],
                    "calinsuredPeriod": "Y1",
                    "calstartDate": "2019-12-14 00:00:00",
                    "calinsuredAge": dt["year"],
                    "socialSecurity": dt["socialSec"],
                    "planLiabilityList": [{
                        "liabilityId": "1010013",
                        "amount": "2000000",
                        "liabilityName": "个人癌症医疗保险(A款）",
                        "liabilityAmount": "200万"
                    }, {
                        "liabilityId": "1010015",
                        "amount": "18000",
                        "liabilityName": "附加癌症住院津贴保险",
                        "liabilityAmount": "100元/天"
                    }],

                    "liabilityContents": [{
                        "liabilityId": "1010013",
                        "amount": "2000000",
                        "liabilityName": "个人癌症医疗保险(A款）",
                        "liabilityAmount": "200万"
                    }, {
                        "liabilityId": "1010015",
                        "amount": "18000",
                        "liabilityName": "附加癌症住院津贴保险",
                        "liabilityAmount": "100元/天"
                    }],

                    "planId": dt["plan"]
                },
                "exchangeData": {
                    "memberId": "",
                    "memberToken": "",
                    "applicationId": "1205299155167756288",
                    "applicationToken": "528951495312b93eeaedd031986987b9",
                    "workqueueId": "1100687673816104960",
                    "channelId": "3",
                    "platformId": "pc",
                    "referId": ""
                }
            }

            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=json.dumps(data))

            if r.status_code == 200:
                totalPrice = r.json()["data"]["sumPremium"]

                price = Helper.decimalParse(totalPrice)

                data = {

                    "name":self.name,
                    "id":dt["id"],
                    "price":price
                }

                self.mysql.updatePrice( data )

                return None

        elif dt["plan"] == "1010A0G202":

            data = {
                "calculateData": {
                    "insuredInfo": [{
                        "calinsuredRelationship": "01",
                        "calinsuredBirth": "2001-10-23",
                        "minimum": 18,
                        "maximum": 80
                    }],
                    "calinsuredPeriod": "Y1",
                    "calstartDate": "2019-12-14 00:00:00",
                    "calinsuredAge": dt["year"],
                    "socialSecurity": dt["socialSec"],
                    "planLiabilityList": [{
                        "liabilityId": "1010013",
                        "amount": "2000000",
                        "liabilityName": "个人癌症医疗保险(A款）",
                        "liabilityAmount": "200万"
                    }, {
                        "liabilityId": "1010014",
                        "amount": "2000000",
                        "liabilityName": "附加癌症扩展特需医疗保险",
                        "liabilityAmount": "200万"
                    }, {
                        "liabilityId": "1010015",
                        "amount": "18000",
                        "liabilityName": "附加癌症住院津贴保险",
                        "liabilityAmount": "100元/天"
                    }],
                    "liabilityContents": [{
                        "liabilityId": "1010013",
                        "amount": "2000000",
                        "liabilityName": "个人癌症医疗保险(A款）",
                        "liabilityAmount": "200万"
                    }, {
                        "liabilityId": "1010014",
                        "amount": "2000000",
                        "liabilityName": "附加癌症扩展特需医疗保险",
                        "liabilityAmount": "200万"
                    }, {
                        "liabilityId": "1010015",
                        "amount": "18000",
                        "liabilityName": "附加癌症住院津贴保险",
                        "liabilityAmount": "100元/天"
                    }],

                    "planId": dt["plan"]
                },
                "exchangeData": {
                    "memberId": "",
                    "memberToken": "",
                    "applicationId": "1205299155167756288",
                    "applicationToken": "528951495312b93eeaedd031986987b9",
                    "workqueueId": "1100687673816104960",
                    "channelId": "3",
                    "platformId": "pc",
                    "referId": ""
                }
            }

            r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=json.dumps(data))

            if r.status_code == 200:
                totalPrice = r.json()["data"]["sumPremium"]

                price = Helper.decimalParse(totalPrice)

                data = {

                    "name": self.name,
                    "id": dt["id"],
                    "price": price
                }

                self.mysql.updatePrice(data)

                return None


    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)

    def test(self):

        items = {'process_date': '2019-12-13 10:43:00', 'message': '保费试算成功', 'refer_url': '', 'data': {
            'planLiabilityList': [{'amount': '2000000', 'liabilityId': '1010013', 'premium': '505.00'},
                                  {'amount': '2000000', 'liabilityId': '1010013', 'premium': '505.00'},
                                  {'amount': '18000', 'liabilityId': '1010015', 'premium': '42.00'}],
            'planId': '1010A0G201', 'sumAmount': '4018000', 'sumPremium': '1052'}, 'code': '0'}

        print(items["data"]["sumPremium"])
